package com.kika.obwiki.controller;

import com.kika.obwiki.rep.UserQueryReq;
import com.kika.obwiki.rep.UserResetPasswordReq;
import com.kika.obwiki.rep.UserSaveReq;
import com.kika.obwiki.rep.UserLoginReq;
import com.kika.obwiki.resp.CommonResp;
import com.kika.obwiki.resp.PageResp;
import com.kika.obwiki.resp.UserQueryResp;
import com.kika.obwiki.resp.UserLoginResp;
import com.kika.obwiki.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kika.obwiki.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSONObject;
import com.kika.obwiki.utils.SaltUtil;
import com.kika.obwiki.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 * 提供用户的增删改查功能
 *
 * @author cr
 * @since 2025-06-22
 */
@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private IUserService userService;

  @Autowired
  private SnowFlake snowFlake;

  @Autowired
  private RedisTemplate redisTemplate;

  private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

  private static final String PASSWORD_KEY = "123456qwer";

  /**
   * 查询用户列表
   * 
   * @param req 查询请求参数
   * @return 分页查询结果
   */
  @GetMapping("/list")
  public CommonResp list(@Valid UserQueryReq req) {
    CommonResp<PageResp<UserQueryResp>> resp = new CommonResp<>(true, "查询成功", null);

    PageResp<UserQueryResp> pageResp = userService.listByname(req);
    resp.setContent(pageResp);

    return resp;
  }

  /**
   * 保存用户信息
   * 
   * @param req 保存请求参数
   * @return 保存结果
   */
  @PostMapping("/save")
  public CommonResp save(@Valid @RequestBody UserSaveReq req) {
    // 生成盐并加盐加密
    String salt = SaltUtil.getSalt();
    String frontMd5 = DigestUtils.md5DigestAsHex((req.getPassword() + PASSWORD_KEY).getBytes());
    String dbPassword = DigestUtils.md5DigestAsHex((frontMd5 + salt).getBytes());
    req.setPassword(dbPassword);
    req.setSalt(salt);
    CommonResp resp = new CommonResp<>(true, "成功", null);
    userService.save(req);
    return resp;
  }

  /**
   * 删除用户
   * 
   * @param id 用户ID
   * @return 删除结果
   */
  @DeleteMapping("/delete/{id}")
  public CommonResp delete(@PathVariable Long id) {
    CommonResp resp = new CommonResp<>(true, "删除成功", null);
    userService.delete(id);
    return resp;
  }

  /**
   * 重置用户密码
   * 
   * @param req 重置密码请求参数
   * @return 重置结果
   */
  @PostMapping("/resetPassword")
  public CommonResp resetPassword(@Valid @RequestBody UserResetPasswordReq req) {
    // 生成新盐并加盐加密
    String salt = SaltUtil.getSalt();
    String frontMd5 = DigestUtils.md5DigestAsHex((req.getPassword() + PASSWORD_KEY).getBytes());
    String dbPassword = DigestUtils.md5DigestAsHex((frontMd5 + salt).getBytes());
    req.setPassword(dbPassword);
    req.setSalt(salt);
    CommonResp resp = new CommonResp<>(true, "成功", null);
    userService.resetPassword(req);
    return resp;
  }

  /**
   * 用户登录接口
   * 
   * @param req 登录请求参数
   * @return 登录响应，包含token
   */
  @PostMapping("/login")
  public CommonResp<UserLoginResp> login(@Valid @RequestBody UserLoginReq req) {
    // 前端已经加密，后端不再加密，直接传给Service层
    CommonResp<UserLoginResp> resp = new CommonResp<>();
    UserLoginResp userLoginResp = userService.login(req);
    Long token = snowFlake.nextId();
    LOG.info("生成单点登录token：{}，并放入redis中", token);
    userLoginResp.setToken(token.toString());

    // Redis操作放在try-catch中，避免连接失败影响登录
    try {
      redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(userLoginResp), 3600 * 24,
          TimeUnit.SECONDS);
    } catch (Exception e) {
      LOG.warn("Redis连接失败，但不影响登录: {}", e.getMessage());
    }

    resp.setContent(userLoginResp);
    return resp;
  }

  /**
   * 用户退出登录接口
   * 
   * @param token 用户token
   * @return 退出登录结果
   */
  @GetMapping("/logout/{token}")
  public CommonResp logout(@PathVariable String token) {
    CommonResp resp = new CommonResp<>();
    redisTemplate.delete(token);
    LOG.info("从redis中删除token: {}", token);
    return resp;
  }

  /**
   * 临时调试接口 - 验证后端连接的数据库内容
   * 
   * @return 所有用户的登录名和密码前缀
   */
  @GetMapping("/debug")
  public String debug() {
    try {
      List<User> users = userService.list();
      StringBuilder result = new StringBuilder();
      result.append("前端密文 (md5('1234' + '123456qwer')): 5aabc85cff2a939221f7c64100b2cd22\n");
      result.append("数据库用户内容:\n");
      for (User user : users) {
        result.append(String.format("用户: %s | 密码: %s | Salt: %s\n",
            user.getLoginName(),
            user.getPassword(),
            user.getSalt()));
      }
      LOG.info("数据库用户内容: {}", result.toString());
      return result.toString();
    } catch (Exception e) {
      LOG.error("调试接口异常", e);
      return "调试接口异常: " + e.getMessage();
    }
  }
}
